package proxypkg

import (
	"fmt"
	"golang.org/x/net/proxy"
	"io/ioutil"
	"net/http"
	"net/url"
	"strings"
	"time"
)

const TestUrl = "https://www.baidu.com"

type Proxyer interface {
	IsProxy(proxyIp string, proxyPort int) (isProxy bool, err error)
}

func CheckProxy(client *http.Client) (isProxy bool, err error){
	res, err := client.Get(TestUrl)
	if err != nil {
		return false, err
	} else {
		defer res.Body.Close()
		if res.StatusCode == 200 {
			body, err := ioutil.ReadAll(res.Body)
			if err == nil && strings.Contains(string(body), "baidu") {
				return true, nil
			} else {
				return false, err
			}
		} else {
			return false, nil
		}
	}
}


type SocksProxy struct {
}

func (SocksProxy) IsProxy(proxyIp string, proxyPort int,proxyUser string,proxyPwd string) (isProxy bool, err error) {
	proxyAddr := fmt.Sprintf("%s:%d", proxyIp, proxyPort)

	var ProxyUser *proxy.Auth

	if proxyUser != "" && proxyPwd != "" {
		ProxyUser = &proxy.Auth{
			User:    proxyUser,
			Password: proxyPwd,
		}
	} else {
		ProxyUser = nil
	}

	dialer, err := proxy.SOCKS5("tcp", proxyAddr, ProxyUser, proxy.Direct)



	client := &http.Client{
		Transport: &http.Transport{
			Dial: dialer.Dial,
		},
		Timeout:  time.Second * time.Duration(5),
	}
	return CheckProxy(client)
}

type HttpProxy struct {
}

func (HttpProxy) IsProxy(proxyIp string, proxyPort int,username string,password string) (isProxy bool, err error) {

	var proxyUrl string
	if username==""{
		proxyUrl = fmt.Sprintf("http://%s:%d", proxyIp, proxyPort)
	}else{
		proxyUrl = fmt.Sprintf("http://%s:%s@%s:%d",username,password, proxyIp, proxyPort)
	}

	proxy, err := url.Parse(proxyUrl)
	if err != nil {
		return false, err
	}
	netTransport := &http.Transport{
		Proxy: http.ProxyURL(proxy),
	}
	client := &http.Client{
		Timeout:   time.Second * 20,  //设置连接超时时间
		Transport: netTransport,
	}
	return CheckProxy(client)
}